<template>
    <el-dialog
        class="ba-operate-dialog"
        :close-on-click-modal="false"
        :model-value="props.show"
        @close="baTable.toggleForm"
        width="80%" 
        :before-close="close"
    >
        <template #header>
            <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']" v-zoom="'.ba-operate-dialog'">
                选择样品
            </div>
        </template>
        <el-scrollbar v-loading="baTable.form.loading" class="ba-table-form-scrollbar" style="">
            <div class="default-main ba-table-box">
                <el-alert class="ba-table-alert" v-if="baTable.table.remark" :title="baTable.table.remark" type="info" show-icon />

                <!-- 表格顶部菜单 -->
                <!-- 自定义按钮请使用插槽，甚至公共搜索也可以使用具名插槽渲染，参见文档 -->
                <TableHeader :buttons="['quickSearch']" quick-search-placeholder="搜索 商品名称">
                    <template #btnBefore>
                        <span style="margin-left: 12px;" class="btn btn-success" @click="confirmSample()">确认选中样品</span>
                    </template>
                    
                </TableHeader>

                <!-- 表格 -->
                <!-- 表格列有多种自定义渲染方式，比如自定义组件、具名插槽等，参见文档 -->
                <!-- 要使用 el-table 组件原有的属性，直接加在 Table 标签上即可 -->
                <Table ref="tableRef" @select="onSelectionChange">
                    <template #size-stock>
                        <!-- 在插槽内，您可以随意发挥，通常使用 el-table-column 组件 -->
                        <el-table-column prop="id" label="尺码/库存" width="270" align="center">
                            <template #default="scope">
                                <div style="">
                                    <table border="1" style="width: 100%; text-align: center; border-color: #fff; font-weight: normal;" cellspacing="0" >
                                        <tr>
                                            <td v-for="(item, key) in scope.row.size_with_stock" :key="key" style="width: 54px;" width="100" v-html="item.size"></td>
                                        </tr>
                                        <tr>
                                            <td v-for="(item, key) in scope.row.size_with_stock" :key="key" style="" v-html="item.stock"></td>
                                        </tr>
                                    </table>
                                </div>
                            </template>
                        </el-table-column>
                    </template>
                    <template #cycle>
                        <!-- 在插槽内，您可以随意发挥，通常使用 el-table-column 组件 -->
                        <el-table-column prop="id" label="生产周期" width="180" align="center">
                            <template #default="scope">
                                <div style="">
                                    <table border="1" style="width: 100%; text-align: center; border-color: #fff;" cellspacing="0" >
                                        <tr>
                                            <td style="width: 50%;">15天</td>
                                            <td style="width: 50%;">30天</td>
                                        </tr>
                                        <tr>
                                            <td>{{ scope.row.cycle_15 }}</td>
                                            <td>{{ scope.row.cycle_30 }}</td>
                                        </tr>
                                    </table>
                                </div>
                            </template>
                        </el-table-column>
                    </template>
                </Table>
            </div>
        </el-scrollbar>
        
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, provide, onMounted, reactive } from 'vue'
import baTableClass from '/@/utils/baTable'

import { baTableApi } from '/@/api/common'
import { useI18n } from 'vue-i18n'
import Table from '/@/components/table/index.vue'
import TableHeader from '/@/components/table/header/index.vue'
import { ElNotification, ElMessageBox } from 'element-plus'

import { saveOrderTemp } from '/@/api/backend/live/index'

const emit = defineEmits(["hideSelectSample", "loadOrderTemp"])

defineOptions({
    name: 'goods/goods',
})



// const selectSampleRef = inject('selectSampleRef')
const { t } = useI18n()
const tableRef = ref()

const state = reactive({
    ids: []
});

interface Props {
    show: boolean
    brand_id: number
    user_id: number
}

const props = defineProps<Props>()

// 确认选中样品
const confirmSample = () => {
    console.log(state.ids);
    
    if(state.ids.length == 0){
        ElNotification({
            message: '未选中任何样品',
            type: 'error',
        });
        return;
    }
    let param = {
        ids: state.ids,
        user_id: props.user_id
    };
    saveOrderTemp(param).then((e) => {
        console.log(e)
        if(e.code != 1){
            ElNotification({
                message: e.msg,
                type: 'error',
            });
            return;
        }
        emit("loadOrderTemp");
        emit("hideSelectSample");
    })
}

// 关闭选择样品的弹窗
const close = (done: () => void) => {
    if(state.ids.length > 0){
        ElMessageBox.confirm('关闭弹窗将放弃使用您已勾选的样品').then(() => {
            emit("hideSelectSample")
            done()
        }).catch(() => { })
    }else{
        emit("hideSelectSample")
        done();
    }
}

// 表格刷新后记住勾选状态
const onSelect = () => {
    let ref = tableRef.value.getRef()
    let index = -1;
    
    console.log(baTable.table.data)
    console.log(state.ids);
    let i = 0; 
    baTable.table.data.map((val) => {
        index = state.ids.indexOf(val.id)
        if(index > -1){
            ref.toggleRowSelection(baTable.table.data![i])
        }
        i++;
    })
}

const onSelectionChange= (selection: TableRow[], row: number) => {
    let current = false;
    selection.map((val) => {
        if(val.id == row.id){
            current = true;
        }
        if(!state.ids.includes(val.id)) {
            state.ids.push(val.id);
        }
    })
    if(current == false){
        state.ids.splice(state.ids.indexOf(row.id), 1);
    }
    console.log(state.ids)

}





/**
 * baTable 内包含了表格的所有数据且数据具备响应性，然后通过 provide 注入给了后代组件
 */
const baTable = new baTableClass(
    new baTableApi('/admin/goods.Goods/'),
    {
        pk: 'id',
        column: [
            { 
                type: 'selection', 
                align: 'center', 
                operator: false,
                
            },
            { label: t('品牌名'), prop: 'brand.name', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', sortable: false },
            { 
                label: t('图片'), 
                render: "image", 
                prop: 'cover', 
                align: 'center', 
                operatorPlaceholder: t('Fuzzy query'), 
                operator: 'LIKE', 
                sortable: false,
                width: 120
            },
            { label: t('商品名'), prop: 'name', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', sortable: false },
            { 
                label: t('颜色'), 
                prop: 'id', 
                align: 'center', 
                operator: false, 
                render: "string" , 
                renderFormatter: (row: TableRow, field: TableColumn, value: any, column: TableColumnCtx<TableRow>, index: number) => {
                    return row.specs[0].color;
                }
            },
            { label: t('官方售价'), prop: 'price', align: 'center', operator: 'RANGE', sortable: false },
            { 
                label: t('供货率'), 
                prop: 'supply_discount', align: 'center', 
                operator: 'RANGE', sortable: false, 
                render: "string" , 
                renderFormatter: (row: TableRow, field: TableColumn, value: any, column: TableColumnCtx<TableRow>, index: number) => {
                    return value == null ? '' : value+'%';
                }
            },
            { label: t('供货价格'), prop: 'supply_price', align: 'center', operator: 'RANGE', sortable: false },
            
        ],
        dblClickNotEditColumn: ['all'],
        defaultOrder: { prop: 'id', order: 'desc' },
    },
    {
        defaultItems: {  },
    },
    {
        getIndex: () => { // 查看前
            
            // baTable.table.filter!.search?.push({ field: 'show_goods', val: 'collection', operator:'=' })
        },
    },
    {
        getIndex: ({ res }: { res: ApiResponse }) => { // 查看后
            setTimeout(function(){
                onSelect()
            }, 500)
        },
    }
)

provide('baTable', baTable)

onMounted(() => {
    baTable.table.ref = tableRef.value
    baTable.mount()
    baTable.table.filter!.show_goods = 'collection';
    baTable.table.filter!.brand_id = props.brand_id;
    baTable.getIndex()?.then(() => {
        baTable.initSort()
        baTable.dragSort()
    })
})
</script>

<style scoped lang="scss">
:deep(.el-image){
    width: 85px;
    height: unset;
}
:deep(.ba-data-table .margin-left-none){
    margin-left: 0!important;
    margin-bottom: 8px;
    padding: 4px 14px;
}
:deep(.ba-data-table .ml-6){
    margin-left: 0!important;
}


:deep(.ba-data-table .margin-left-none:last-child){
    margin-bottom: 0px;
}
:deep(.table-operate-text){
    padding-left: 0;
}
:deep(.font-size-13){
    font-size: 13px;
}

</style>
